/*
 * @Author: your name
 * @Date: 2020-04-23 20:30:15
 * @LastEditTime: 2020-05-07 10:00:09
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \my-admin\src\route\index.js
 */


import vueRouter from 'vue-router'
import Vue from 'vue'
import {getToken} from '../config/auth'
import login from '../pages/login'
import api from '../api/api'
import store from '../store'

Vue.use(vueRouter)



const routes = [
    {
        path: '/login',
        name: 'Login',
        component: login
    },
    {
        path: '/',
        name: 'Login1',
        component: login
    },
    { 
        path: '/404',
        component: () => import('../pages/404'), 
        hidden: true 
    }
]

const router = new vueRouter({
    mode:'history',
    routes
})
const whiteList = ['/login'] // 不重定向白名单
router.beforeEach((to,from,next) => {
    if(getToken('Token') && getToken('Token') != 'undefined'){
        if(to.path == '/login') {
            next()
        } else {
            api.verifyToken({}).then(data => {
                if(data.state){
                    store.dispatch('GenerateRoutes',{"roles":data.roleId}).then(() => {
                        if(to.matched.length) return next()
                        router.addRoutes(store.getters.allStore) // 动态添加可访问权限路由表
                        next({ ...to, replace: true }) 
                    });
                } else {
                    next({path:"/login"})
                }
                 
            }).catch((err) => {
            })
        }
    } else {
        console.log(to.path)
        if(to.path!=="/login"){
            next('/login');
        } else {
            next()
        }
        // if (whiteList.indexOf(to.path) != -1) {
        //     // 点击退出时,会定位到这里
        //     next({ path: '/login' })
        //   } else {
        //     next({ path: '/login' })
        //   } 
    }
})
// router.addRoutes(adminTeacher)
export default router